//
//  Waterfall.m
//  测试小型VIEW的加载
//
//  Created by yishangpin2 on 15/3/4.
//  Copyright (c) 2015年 yishangpin2. All rights reserved.
//

#import "Waterfall.h"
#import "YRSideViewController.h"
#import "AppDelegate.h"
#import "BuyView.h"

#define brim 5   //边缘

@implementation Waterfall{

    AppDelegate *delegate ;
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


-(void)ViewframSetX:(int)setX SetY:(int)setY Pic:(UIImage*)image delegateW:(float)width{
    //最初隐藏加载状态图
    _Activity.hidden = YES;
    delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    _pic.image = image;
    
    _pic.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTapped)];
    [_pic addGestureRecognizer:singleTap];//点击图片事件
    
    
    UIImage *smallimage = [self imageCompressForWidth:image targetWidth:width/2 - brim*2];
    
    _pic.frame = CGRectMake(brim,brim,smallimage.size.width,smallimage.size.height);
    _smallview.frame = CGRectMake(brim, _pic.frame.size.height+5, width/2 - brim*2, 65);
    self.frame = CGRectMake(setX, setY, width/2, _pic.frame.size.height+75);
    _viewY = self.frame.size.height;

    //设置收藏按钮的样式
    for(NSString *tag in delegate.CollectArray) {
        if ([tag isEqualToString:[NSString stringWithFormat:@"%ld",(long)self.tag]]) {
            [_Collect setImage:[UIImage imageNamed:@"打钩.png"] forState:0];
            [_Collect setTitle:@" Edit List" forState:0 ];
        }
    }
}


-(void)photoTapped{

    [[NSNotificationCenter defaultCenter] postNotificationName:@"Buy" object:[NSString stringWithFormat:@"%ld", (long)self.tag]];
    

}

#pragma mark - 设置价格
-(void)SetOldPrice:(float)oldprice SetNewPrice:(float)newprice{
    
    
//加个中间添加横线
    _OriginalCost.textAlignment = NSTextAlignmentCenter;
    NSString *Price = [NSString stringWithFormat:@"$ %.0f",oldprice];
    NSUInteger length = [Price length];
    
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:Price];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, length)];
    [_OriginalCost setAttributedText:attri];
    
    
    [_CurrentPrice setText:[NSString stringWithFormat:@"$ %.0f",newprice]];
    
}

#pragma mark - 图片按照指定宽度 等比例缩放图片，自动调整图片高度

-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = defineWidth;
    
    CGFloat targetHeight = height / (width / targetWidth);
    
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        
        if(widthFactor > heightFactor){
            
            scaleFactor = widthFactor;
            
        }
        
        else{
            
            scaleFactor = heightFactor;
            
        }
        
        scaledWidth = width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        
        if(widthFactor > heightFactor){
            
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
            
        }else if(widthFactor < heightFactor){
            
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    
    UIGraphicsBeginImageContext(size);
    
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width = scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    
    [sourceImage drawInRect:thumbnailRect];
    
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    if(newImage == nil){
        
        
        NSLog(@"scale image fail");
        
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

#pragma mark - 收藏按钮点击事件

- (IBAction)Collect:(id)sender {
    
    if ([_Collect.titleLabel.text isEqualToString:@"  Save"]) {
        _Collect.hidden = YES;
        _Activity.hidden = NO;
        [_Activity startAnimating];
        
        [self addCollect:[NSString stringWithFormat:@"%ld",(long)self.tag]];
    //延迟0.5秒执行
    [self performSelector:@selector(succeed) withObject:nil afterDelay:1.0f];
    
    }
    
    else
    {
        [self succeed];
    }
}

#pragma mark - 收藏成功后，弹出“成功”图片提示

-(void)succeed{

    [_Activity stopAnimating];
    _Activity.hidden = YES;
    _Collect.hidden = NO;

    if ([_Collect.titleLabel.text isEqualToString:@"  Save"]) {
        _CorrectImage.hidden = NO;
        [_Collect setImage:[UIImage imageNamed:@"打钩.png"] forState:0];
        [_Collect setTitle:@" Edit List" forState:0 ];
        
        [self performSelector:@selector(hide) withObject:nil afterDelay:0.5f];
    }
    else {
//        [_Collect setImage:[UIImage imageNamed:@"xiaoaixin.png"] forState:0];
//        [_Collect setTitle:@"  Save" forState:0 ];
        
        //把图片的tag值赋给代理
        delegate.collectTag = self.tag;
        
        YRSideViewController *sideViewController=[delegate sideViewController];
        sideViewController.rightViewController.CreateWishlist = @"Create Wishlist";
        [sideViewController showRightViewController:true];
        
        //显示removeButton
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showRemoveView" object:nil];
        //把选中的对象赋给代理，修改收藏图标
        delegate.waterfall = self;
    }

}

#pragma mark - 将收藏数据写入沙河 （测试时使用）

-(void)addCollect:(NSString *)tag{
    delegate = [[UIApplication sharedApplication]delegate];
    [delegate.CollectArray addObject:tag];
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/collect.plist",NSHomeDirectory()];
    [delegate.CollectArray writeToFile:filePath atomically:YES];
    NSLog(@"%@",delegate.CollectArray);

}


//淡出的动画效果
-(void)hide{
    
    [UIView transitionWithView:_CorrectImage duration:0.6 options:UIViewAnimationOptionTransitionCrossDissolve //change to whatever animation you like
                    animations:^ {
                        _CorrectImage.hidden = YES ;
                    }
                    completion:nil];

}


- (IBAction)clickBuyButton:(id)sender {
    
    
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BuyView" owner:self options:nil];
    BuyView *buyview = nib[0];
    buyview.frame = CGRectMake(0, 0, delegate.width, delegate.height);
    UIViewController *viewcontroller = [delegate CurrentViewController].viewControllers[[delegate CurrentViewController].viewControllers.count-1];
    [viewcontroller.view addSubview:buyview];
    delegate.buyview = buyview;
    
    delegate.tag = self.tag;
}
@end
